package com.Packet
{
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	
	

	//解析
	public class PacketDecoder
	{
		private var _value:Array;
		
		public function PacketDecoder(_byte:ByteArray)
		{
			_value = new Array();
			
			_byte.endian =  Endian.LITTLE_ENDIAN;
			
			var bytes:int = _byte.bytesAvailable;
			var type:int;
			var L:int;
			
			while (bytes)
			{
				type = _byte.readByte();
				//trace("type", type);
				
				switch(type)
				{
					case PacketDataType.TYPE_INT:
						_value.push(_byte.readInt());
						break;
					case PacketDataType.TYPE_FLOAT:
						_value.push(_byte.readFloat());
						break;
					case PacketDataType.TYPE_STRING:
						L = _byte.readInt();
						//trace("String ",L)
						_value.push(_byte.readUTFBytes(L));
						break;
					case PacketDataType.TYPE_WIDESTR:
						L = _byte.readInt();
						var btte:ByteArray = new ByteArray();
						_byte.readBytes(btte,0,uint(L));
						_value.push(wstr2utf(btte));
						break;
					case PacketDataType.TYPE_BINARY:
						L = _byte.readInt();
						var btte2:ByteArray = new ByteArray();
						_byte.readBytes(btte2,0,uint(L));
						_value.push(btte2);
						break;
				}
				bytes = _byte.bytesAvailable;
			}
		}
		
		private function wstr2utf(ba:ByteArray):String
		{
			var L:int = ba.length -2;//减去最后的两个结束符
			L = L/2;
			var re:String = "";
			for(var i:int; i<L; i++)
			{
				var item:ByteArray = new ByteArray();
				//刚好倒过来的 
				item[0] = ba[1 + i*2];
				item[1] = ba[0 + i*2];
				var t:int = int(item[0]<<8) + item[1];
				re += String.fromCharCode(t);
			}
			return re;
		}
		
		public function getValue():Array
		{
			return _value;
		}
		
	}
}